package org.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.dao.TeacherDao;
import org.example.entity.TeacherEntity;
import org.example.config.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherDao, TeacherEntity> implements TeacherService {

    @Autowired
    private TeacherDao teacherDao;

    @Override
    public boolean addTeacher(TeacherEntity teacherEntity) {
        // 使用 MD5 加密密码
        teacherEntity.setPassword(MD5Utils.encrypt(teacherEntity.getPassword()));
        return teacherDao.insert(teacherEntity) > 0;
    }

    @Override
    public boolean updateTeacher(TeacherEntity teacherEntity) {
        // 如果密码字段不为空，则加密后更新
        if (teacherEntity.getPassword() != null) {
            teacherEntity.setPassword(MD5Utils.encrypt(teacherEntity.getPassword()));
        }
        return teacherDao.updateById(teacherEntity) > 0;
    }

    @Override
    public TeacherEntity login(String username, String password) {
        QueryWrapper<TeacherEntity> queryWrapper = Wrappers.query();
        queryWrapper.eq("tea_realname", username); // 假设数据库字段是teacher_realname
        TeacherEntity teacher = teacherDao.selectOne(queryWrapper);
        // 检查用户是否存在并验证密码
        if (teacher != null && MD5Utils.encrypt(password).equals(teacher.getPassword())) {
            return teacher;
        }
        return null;
    }

    @Override
    public boolean deleteTeacher(Integer teacherId) {
        return teacherDao.deleteById(teacherId) > 0;
    }

    @Override
    public TeacherEntity getTeacherById(Integer teacherId) {
        return teacherDao.selectById(teacherId);
    }

    @Override
    public List<TeacherEntity> getAllTeachers() {
        return teacherDao.selectList(null);
    }
}
